﻿using HAF.LogUtility;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.ComponentModel;
using System.IO;

namespace TarManager
{
    /// <summary>
    /// 文件压缩类
    /// </summary>
    [DisplayName("文件加解压帮助类")]
    public class SharpZipper
    {
        #region 解压
        /// <summary>
        /// 文件解压
        /// </summary>
        /// <param name="zipPath">压缩文件路径</param>
        /// <param name="goalFolder">解压到的目录</param>
        /// <returns></returns>
        public static bool UnzipTgz(string zipPath, string goalFolder)
        {
            if (!File.Exists(zipPath))
            {
                LogHelper.WriteErrorLog("文件不存在{0}", zipPath);
                return false;
            }
            LogHelper.WriteInfoLog("解压文件{0}到指定文件夹{1}", zipPath, goalFolder);

            if (!Directory.Exists(goalFolder))
            {
                Directory.CreateDirectory(goalFolder);
            }

            Stream inStream = null;
            Stream gzipStream = null;
            TarArchive tarArchive = null;
            try
            {
                using (inStream = File.OpenRead(zipPath))
                {
                    using (gzipStream = new GZipInputStream(inStream))
                    {
                        tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
                        tarArchive.ExtractContents(goalFolder);
                        tarArchive.Close();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("压缩出错！");
                return false;
            }
            finally
            {
                if (null != tarArchive) tarArchive.Close();
                if (null != gzipStream) gzipStream.Close();
                if (null != inStream) inStream.Close();
            }
        }

        /// <summary>  
        /// tar包解压  
        /// </summary>  
        /// <param name="strFilePath">tar包全路径</param>  
        /// <param name="strUnpackDir">解压到的目录</param>  
        /// <returns></returns>  
        public static bool UnpackTarFile(string strFilePath, string strUnpackDir)
        {
            try
            {
                if (!File.Exists(strFilePath))
                {
                    return false;
                }

                strUnpackDir = strUnpackDir.Replace("/", "\\\\");
                if (!strUnpackDir.EndsWith("\\\\"))
                {
                    strUnpackDir += "\\\\";
                }

                if (!Directory.Exists(strUnpackDir))
                {
                    Directory.CreateDirectory(strUnpackDir);
                }

                FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ICSharpCode.SharpZipLib.Tar.TarInputStream s = new TarInputStream(fr);
                TarEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (directoryName != String.Empty)
                        Directory.CreateDirectory(strUnpackDir + directoryName);

                    if (fileName != String.Empty)
                    {
                        FileStream streamWriter = File.Create(strUnpackDir + theEntry.Name);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                    }
                }
                s.Close();
                fr.Close();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        
        /// <summary> 
        /// 解压功能(解压压缩文件到指定目录) 
        /// </summary> 
        /// <param name="sourceZip">zip文件全路径</param> 
        /// <param name="targetFolder">解压输出目录</param> 
        /// <param name="password">解压密码</param>
        /// <param name="isPackDirectory">使用压缩包名做目录</param>
        /// <returns>是否成功</returns> 
        public static bool UnpackZipFile(string sourceZip, string targetFolder, string password = null, bool isPackDirectory = true)
        {
            //待解压文件校验
            if (string.IsNullOrEmpty(sourceZip) || !System.IO.File.Exists(sourceZip))
            {
                return false;
            }
            //解压文件格式判断
            string fileExt = Path.GetExtension(sourceZip);
            if (fileExt.ToLower().IndexOf("zip") <= 0)
            {
                return false;
            }

            if (isPackDirectory)
            {
                string packName = Path.GetFileNameWithoutExtension(sourceZip);
                targetFolder = Path.Combine(targetFolder, packName);
            }
            //输出目录校验
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }
            //输出目录补全
            if (!targetFolder.EndsWith("\\"))
            {
                targetFolder += "\\";
            }
            LogHelper.WriteDebugLog("当前线程输入文件为{0}，输出目录为{1}", sourceZip, targetFolder);
            //TO-DO:大文件的效率问题
            /*
             * 遇到大文件会占用过多的内存，所以应该采取分块读取文件的方式：即使用fs.Seek分块读取文件并放到内存中，然后每块分别写到ZIP文件中，这样每次最大消耗也只有该块的大小。
             * */
            ZipEntry ent = null;
            using (var zipStream = new ZipInputStream(System.IO.File.OpenRead(sourceZip)))
            {
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (ent.IsDirectory)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(ent.Name))
                    {
                        continue;
                    }
                    string fileName = targetFolder + ent.Name.Replace('/', '\\');
                    var index = ent.Name.LastIndexOf('/');
                    if (index != -1)
                    {
                        string path = targetFolder + ent.Name.Substring(0, index).Replace('/', '\\');
                        System.IO.Directory.CreateDirectory(path);
                    }
                    var bytes = new byte[ent.Size];
                    zipStream.Read(bytes, 0, bytes.Length);
                    System.IO.File.WriteAllBytes(fileName, bytes);
                }
            }
            GC.Collect(1);
            return true;
        }

        /// <summary>
        /// 解压资源文件
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="fileToUnZip">被解压文件</param>
        /// <param name="zipedFolder">解压到指定文件夹</param>
        /// <param name="password">解压密码</param>
        [DisplayName("解压资源文件")]
        public static void UnZip(string taskId, string fileToUnZip, string zipedFolder, string password)
        {
            if (!File.Exists(fileToUnZip))
            {
                LogHelper.WriteErrorLogExt(taskId, "文件不存在{0}", fileToUnZip);
                return;
            }
            LogHelper.WriteInfoLogExt(taskId, "解压文件{0}到指定文件夹{1}", fileToUnZip, zipedFolder);

            if (!Directory.Exists(zipedFolder))
            {
                Directory.CreateDirectory(zipedFolder);
            }

        }
        #endregion

        private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string ParentFloderName)
        {
            bool res = true;
            string[] floders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            //Crc32 crc = new Crc32();
            try
            {
                //创建当前文件夹
                entry = new ZipEntry(Path.Combine(ParentFloderName, Path.GetFileName(folderToZip) + "/"));
                //加“/”才会当成时文件夹创建
                s.PutNextEntry(entry);
                s.Flush();
                //先压缩文件，再递归压缩文件夹
                filenames = Directory.GetFiles(folderToZip);
                foreach (string file in filenames)
                {
                    //打开压缩文件
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFloderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    //crc.Reset();
                    //crc.Update(buffer);
                    //entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {

                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            floders = Directory.GetDirectories(folderToZip);
            foreach (string folder in floders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFloderName, Path.GetFileName(folderToZip))))
                {
                    return false;
                }
            }
            return res;
        }

        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, string password)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
            {
                return false;
            }
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(6);
            s.Password = password;
            res = ZipFileDictory(FolderToZip, s, "");
            s.Flush();
            s.Close();
            return res;
        }

        private static bool ZipFile(string fileToZip, string ZipedFile, string Password)
        {
            if (!File.Exists(fileToZip))
            {
                throw new FileNotFoundException("指定要压缩的文件： " + fileToZip + " 不存在！");
            }
            FileStream zipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry zipentry = null;
            bool res = true;
            try
            {
                zipFile = File.OpenRead(fileToZip);
                byte[] buffer = new byte[zipFile.Length];
                zipFile.Read(buffer, 0, buffer.Length);
                zipFile.Close();
                zipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(zipFile);
                ZipStream.Password = Password;
                zipentry = new ZipEntry(Path.GetFileName(fileToZip));
                ZipStream.PutNextEntry(zipentry);
                ZipStream.SetLevel(6);
                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
                res = false;
            }
            finally
            {
                if (zipentry != null)
                {
                    zipentry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Flush();
                    ZipStream.Close();
                }
                if (zipFile != null)
                {
                    zipFile.Close();
                    zipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return res;
        }

        /// <summary>
        /// 文件夹打包
        /// </summary>
        /// <param name="FileToZip">待打包文件夹</param>
        /// <param name="zipedFile">包文件名称</param>
        /// <param name="Password">包密码</param>
        /// <returns></returns>
        public static bool Zip(string FileToZip, string zipedFile, string Password)
        {
            if (Directory.Exists(FileToZip))
            {
                return ZipFileDictory(FileToZip, zipedFile, Password);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, zipedFile, Password);
            }
            else
            {
                return false;
            }
        }

        #region 压缩
        /// <summary> 
        /// 压缩文件夹  
        /// </summary> 
        /// <param name="folderToZip">要压缩的文件夹路径</param> 
        /// <param name="Stream">压缩前的Stream,方法执行后变为压缩完成后的文件</param> 
        /// <param name="password">密码</param> 
        /// <returns>是否成功</returns> 
        public static bool ZipDirectoryToStream(string folderToZip, Stream Stream, string password = null)
        {
            return ZipDirectoryToZipStream(folderToZip, Stream, password) != null;
        }

        /// <summary> 
        /// 压缩文件夹  
        /// </summary> 
        /// <param name="folderToZip">要压缩的文件夹路径</param> 
        /// <param name="Stream">压缩前的Stream,方法执行后变为压缩完成后的文件</param> 
        /// <param name="password">密码</param> 
        /// <returns>是否压缩成功返回ZipOutputStream，否则返回null</returns> 
        public static ZipOutputStream ZipDirectoryToZipStream(string folderToZip, Stream Stream, string password = null)
        {
            if (!Directory.Exists(folderToZip))
            {
                return null;
            }
            ZipOutputStream zipStream = new ZipOutputStream(Stream);
            zipStream.SetLevel(6);
            if (!string.IsNullOrEmpty(password))
            {
                zipStream.Password = password;
            }
            if (ZipDirectory(folderToZip, zipStream, ""))
            {
                zipStream.Finish();
                return zipStream;
            }
            GC.Collect(1);
            return null;
        }

        /// <summary> 
        /// 递归压缩文件夹的内部方法 
        /// </summary> 
        /// <param name="folderToZip">要压缩的文件夹路径</param> 
        /// <param name="zipStream">压缩输出流</param> 
        /// <param name="parentFolderName">此文件夹的上级文件夹</param> 
        /// <returns>是否成功</returns> 
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
        {
            var crc = new ICSharpCode.SharpZipLib.Checksum.Crc32();

            //这段是创建空文件夹,注释掉可以去掉空文件夹(因为在写入文件的时候也会创建文件夹)
            //if (!string.IsNullOrEmpty(parentFolderName))
            //{
            //    ent = new ZipEntry(parentFolderName + "/");
            //    zipStream.PutNextEntry(ent);
            //    zipStream.Flush();
            //}

            var files = Directory.GetFiles(folderToZip);
            foreach (string file in files)
            {
                byte[] buffer = File.ReadAllBytes(file);
                var ent = new ZipEntry(parentFolderName + "/" + Path.GetFileName(file));
                //ent.DateTime = File.GetLastWriteTime(file);//设置文件最后修改时间
                ent.DateTime = DateTime.Now;
                ent.Size = buffer.Length;

                crc.Reset();
                crc.Update(buffer);

                ent.Crc = crc.Value;
                zipStream.PutNextEntry(ent);
                zipStream.Write(buffer, 0, buffer.Length);
            }

            var folders = Directory.GetDirectories(folderToZip);
            foreach (var folder in folders)
            {
                var _parentFolderName = parentFolderName + "\\" + folder.Substring(folder.LastIndexOf('\\') + 1);
                if (!ZipDirectory(folder, zipStream, _parentFolderName))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> 
        /// 压缩文件夹  
        /// </summary> 
        /// <param name="folderToZip">要压缩的文件夹路径</param> 
        /// <param name="zipedFile">压缩文件完整路径</param> 
        /// <param name="password">密码</param> 
        /// <returns>是否成功</returns> 
        public static bool ZipDirectory(string folderToZip, string zipedFile, string password = null)
        {
            var zipStream = ZipDirectoryToZipStream(folderToZip, new FileStream(zipedFile, FileMode.Create, FileAccess.Write), password);
            if (zipStream == null)
            {
                return false;
            }
            zipStream.Close();
            return true;
        }

        /// <summary> 
        /// 压缩文件 
        /// </summary> 
        /// <param name="fileToZip">要压缩的文件全名</param> 
        /// <param name="zipedFile">压缩后的文件名</param> 
        /// <param name="password">密码</param> 
        /// <returns>是否成功</returns> 
        public static bool ZipFile1(string fileToZip, string zipedFile, string password = null)
        {
            if (!File.Exists(fileToZip))
            {
                return false;
            }
            var fs = File.OpenRead(fileToZip);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();

            fs = File.Create(zipedFile);
            var ent = new ZipEntry(Path.GetFileName(fileToZip));
            using (var zipStream = new ZipOutputStream(fs))
            {
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }
                zipStream.PutNextEntry(ent);
                zipStream.SetLevel(6);
                zipStream.Write(buffer, 0, buffer.Length);
            }

            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }

            GC.Collect(1);

            return true;
        }

        /// <summary> 
        /// 压缩文件或文件夹 
        /// </summary> 
        /// <param name="fileToZip">要压缩的路径</param> 
        /// <param name="zipedFile">压缩后的文件名</param> 
        /// <param name="password">密码</param> 
        /// <returns>是否成功</returns> 
        public static bool Zip1(string fileToZip, string zipedFile, string password = null)
        {
            if (Directory.Exists(fileToZip))
            {
                return ZipDirectory(fileToZip, zipedFile, password);
            }
            else if (File.Exists(fileToZip))
            {
                return ZipFile(fileToZip, zipedFile, password);
            }
            return false;
        }
        #endregion
    }
}
